//
//  HWUtilties.m
//  嗨文
//
//  Created by 响当当 on 2019/1/8.
//  Copyright © 2019年 dongzheng. All rights reserved.
//

#import "HWUtilties.h"
#import "CXAlertView.h"
#import "HWCommonWebViewController.h"
#import <WebKit/WebKit.h>
#import "HWUpdateAppView.h"

#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>

@implementation HWUtilties

+ (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [HWUtilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [HWUtilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [HWUtilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [HWUtilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"GPRS网络");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"wifi网络");
            }
                break;
            default:
                break;
        }
        
    }];
}

/**
 * 获取当前屏幕显示的viewcontroller
 */
+ (UIViewController *)getCurrentVC
{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

+ (void)showAlertWithTitle:(NSString *)titleStr
                   content:(NSString *)eventStr
               buttonTitle:(NSString *)btnTitle
            cancelBtnTitle:(NSString *)cancelBtnTitle
          ConfirmWithBlock:(void(^)(void))comfirm
{
    
    CXAlertView *alterview = [[CXAlertView alloc]initWithTitle:titleStr message:eventStr cancelButtonTitle:cancelBtnTitle];
    
    [alterview addButtonWithTitle:btnTitle type:CXAlertViewButtonTypeDefault handler:^(CXAlertView *alertView, CXAlertButtonItem *button) {
        [alertView dismiss];
        
        comfirm();
        
    }];
    [alterview show];
}

/*
 ** 提示操作,不含取消
 
 */
+ (void)showAlertWithTitle:(NSString *)titleStr
                   content:(NSString *)eventStr
               buttonTitle:(NSString *)btnTitle
          ConfirmWithBlock:(void(^)(void))comfirm
{
    
    CXAlertView *alterview = [[CXAlertView alloc]initWithTitle:titleStr message:eventStr cancelButtonTitle:nil];
    [alterview addButtonWithTitle:btnTitle type:CXAlertViewButtonTypeDefault handler:^(CXAlertView *alertView, CXAlertButtonItem *button) {
        [alertView dismiss];
        comfirm();
    }];
    [alterview show];
}

/**
 *    url跳转
 */
+ (void)openUrlSchedule:(NSString *)urlStr
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
}

//这个函数就是将字典封装成转义的JSON字符串
+ (NSString *)toJSONString:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}


//创建label
+ (UILabel *)creatLabelWithFrame:(CGRect)Rect
                    textAligment:(NSTextAlignment)textAligment
                        textClor:(UIColor *)color
                        textFont:(CGFloat)size
{
    UILabel *label = [[UILabel alloc]initWithFrame:Rect];
    label.textAlignment = textAligment;
    label.textColor = color;
    label.font = [UIFont systemFontOfSize:size];
    return label;
}

//创建button
+ (UIButton *)creatButtonWithFrame:(CGRect)Rect
                      textAligment:(NSTextAlignment)textAligment
                              text:(NSString *)title
                          textClor:(UIColor *)color
                         buttonBGC:(UIColor *)bgcColor
                          textFont:(CGFloat)size
                            target:(id)vc
                            method:(SEL)method
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = Rect;
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:size]];
    [button.titleLabel setTextAlignment:textAligment];
    [button setBackgroundColor:bgcColor];
    [button addTarget:vc action:method forControlEvents:UIControlEventTouchUpInside];
    return button;
}


//获取当前年月
+ (NSString *)getYearAndMonth
{
    NSDate *date =[NSDate date];//简书 FlyElephant
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
//    [formatter setDateFormat:@"dd"];
//    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    
    return [NSString stringWithFormat:@"%ld年%ld月",currentYear,currentMonth];
    
}


//电话号码
+ (BOOL)checkTel:(NSString *)mobileNumbel

{
    if (!mobileNumbel)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
        
        DISMISS_SVP(1.2f);
        
        return NO;
        
    }else{
        
        if (mobileNumbel.length == 11) {
            
            return true;
        }
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        DISMISS_SVP(1.2f);
        return false;
    }
}


//时间戳转换成时间
+ (NSString *)getTime:(NSString *)time
{
    NSTimeInterval interval = [time doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate: date];
    
    return dateString;
}

/**
 *  push web
 */
+ (void)pushWebWithUrl:(NSString *)urlStr title:(NSString *)title toUrl:(NSString *)toUrl toId:(NSString *)toId
{
    HWCommonWebViewController *tag = [[HWCommonWebViewController alloc]init];
    tag.urlStr = urlStr;
    tag.titleStr = title;
    tag.toUrl = toUrl;
    tag.toId = toId;
    tag.hidesBottomBarWhenPushed = YES;
    [[HWUtilties getCurrentVC].navigationController pushViewController:tag animated:nil];
}

+ (void)removeCookie
{
    
    if (@available(iOS 9.0, *)) {//iOS9及以上
        WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
        [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
                         completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
                             for (WKWebsiteDataRecord *record in records)
                             {
                                 if ([record.displayName containsString:@"woomou.com"])
                                 {
                                     [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes
                                                                               forDataRecords:@[record]
                                                                            completionHandler:^{
                                                                                NSLog(@"Cookies for %@ deleted successfully",record.displayName);
                                                                            }];
                                 }
                                 
                             }
                         }];
    }else { //iOS9以下
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}

+ (NSString *)adjustParagraphFormat:(NSString *)string
{
    if (!string) {
        return nil;
    }
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@"\r\n"];
    return string;
}

+(NSArray *)pagingWithContentString:(NSString *)contentString contentSize:(CGSize)contentSize textAttribute:(NSDictionary *)textAttribute
{
    
    NSMutableArray *pageArray = [NSMutableArray array];
    NSMutableAttributedString *orginAttributeString = [[NSMutableAttributedString alloc]initWithString:contentString attributes:textAttribute];
    NSTextStorage *textStorage = [[NSTextStorage alloc]initWithAttributedString:orginAttributeString];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc]init];
    [textStorage addLayoutManager:layoutManager];
    int i=0;
    while (YES) {
        i++;
        NSTextContainer *textContainer = [[NSTextContainer alloc]initWithSize:contentSize];
        [layoutManager addTextContainer:textContainer];
        NSRange rang = [layoutManager glyphRangeForTextContainer:textContainer];
        
        if(rang.length <= 0)
        {
            break;
        }
        NSString *str = [contentString substringWithRange:rang];
        NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc]initWithString:str attributes:textAttribute];
        [pageArray addObject:attstr];
    }
    
    return pageArray;
    
}

//获取手机的网络的ip地址
+ (NSString *)getIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
                    NSLog(@"IP:%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]);
                return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

//url encode 编码
+(NSString*)encodeString:(NSString*)unencodedString
{

    NSString *charactersToEscape = @"#[]@!$'()*+;\"<>%{}|^~`/";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *encodedUrl = [[unencodedString description] stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    return encodedUrl;
}

+(NSString *)URLDecodedString:(NSString *)str
{
    return [str stringByRemovingPercentEncoding];
}


//获取当前时间戳  （以毫秒为单位）

+(NSString *)getNowTimeTimestamp3
{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
    
}


//json字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

//字典转json字符串
+ (NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

//埋点
+ (void)buryPointWithStayTime:(NSString *)stayTime
              timestamp:(NSString *)timestamp
               memberId:(NSString *)memberId
               fromUrl:(NSString *)fromUrl
               toUrl:(NSString *)toUrl
               fromId:(NSString *)fromId
               toId:(NSString *)toId
{
    NSString *jsonStr = [NSString stringWithFormat:@"{\"stayTime\":%@,\"timestamp\":%@,\"memberId\":%@,\"fromUrl\":\"%@\",\"toUrl\":\"%@\",\"fromId\":\"%@\",\"toId\":\"%@\",\"dataType\":%@,\"network\":%@,\"softwareType\":%@,\"client\":%@,\"ipAddr\":\"%@\"}",stayTime,timestamp,current_User.userID,fromUrl,toUrl,fromId,toId,@"1",@"1",@"3",@"3",[HWUtilties getIPAddress]];
    
    NSDictionary *prarmers = @{
                               @"jsonData" : jsonStr
                               };
    
    [PointManager haiBookShelfPoint:prarmers sucess:^(id  _Nonnull acceptData) {
        NSLog(@"埋点成功");
    } fail:^(NSError * _Nullable error) {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showErrorWithStatus:@"获取失败，请检查网络是否良好"];
        DISMISS_SVP(1.0f);
    }];
}

//文章埋点
+ (void)buryPointWithStayTime:(NSString *)stayTime
                    timestamp:(NSString *)timestamp
                     memberId:(NSString *)memberId
                      fromUrl:(NSString *)fromUrl
                        toUrl:(NSString *)toUrl
                       fromId:(NSString *)fromId
                         toId:(NSString *)toId
                    articleId:(NSString *)articleId
                    chapterId:(NSString *)chapterId
                 chapterTotal:(NSString *)chapterTotal
{
    NSString *jsonStr = [NSString stringWithFormat:@"{\"stayTime\":%@,\"timestamp\":%@,\"memberId\":%@,\"fromUrl\":\"%@\",\"toUrl\":\"%@\",\"fromId\":\"%@\",\"toId\":\"%@\",\"dataType\":%@,\"network\":%@,\"softwareType\":%@,\"client\":%@,\"ipAddr\":\"%@\",\"articleId\":%@,\"chapterId\":%@,\"chapterTotal\":%@}",stayTime,timestamp,current_User.userID,fromUrl,toUrl,fromId,toId,@"1",@"1",@"3",@"3",[HWUtilties getIPAddress],articleId,chapterId,chapterTotal];
    
    NSDictionary *prarmers = @{
                               @"jsonData" : jsonStr
                               };
    
    [PointManager haiBookShelfPoint:prarmers sucess:^(id  _Nonnull acceptData) {
        NSLog(@"埋点成功");
    } fail:^(NSError * _Nullable error) {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showErrorWithStatus:@"获取失败，请检查网络是否良好"];
        DISMISS_SVP(1.0f);
    }];
}


+ (void)alterUpDateApp
{
    if (![[HWUtilties getCurrentVC] isKindOfClass:[UIAlertController class]]) {
        NSString *appCurVersion = appVersion;
        NSArray *versonArr = [appCurVersion componentsSeparatedByString:@"."];
        NSInteger appCurVersionNum = [[versonArr componentsJoinedByString:@""] integerValue];
        [NetWorkingManager postRequestUrl:FULL_WEB_URL(@"user/iosversion") withPramater:nil sucess:^(id responseObject) {
            NSDictionary *responseDic = IFNULL(responseObject[@"data"], [NSDictionary dictionary]);
            NSString *newVersion = IFNULL(responseDic[@"version"], @"");
            NSArray *newVersionArr = [newVersion componentsSeparatedByString:@"."];
            NSInteger newVersionNum = [[newVersionArr componentsJoinedByString:@""] integerValue];
            NSString *remark = IFNULL(responseDic[@"remark"], @"发现新版本,赶紧更新!");
            NSArray *remarkList = [remark componentsSeparatedByString:@","];
            NSNumber *isForce = IFNULL(responseDic[@"isForce"], @0);
            if (appCurVersionNum < newVersionNum) {
//                if ([isForce isEqual:@0]) {
//                    [[HWUpdateAppView alertUpDateView] showOptional:remarkList];
//                }else if ([isForce isEqual:@1]) {
//                    [[LCAlertUpDateView alertUpDateView] showForce:remarkList];
//                }
                HWUpdateAppView *view = [[HWUpdateAppView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KScreenHeight)];
                [[UIApplication sharedApplication].keyWindow addSubview:view];
            }
        } failure:^(NSError *error) {
            
        }];
    }
}
@end
